package com.jeesite.modules.sd.web;

import com.alibaba.fastjson.JSON;
import com.jeesite.common.codec.AesUtils;
import com.jeesite.common.codec.DesUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Extend;
import com.jeesite.common.entity.Page;
import com.jeesite.common.mybatis.mapper.query.QueryType;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sd.common.constants.FileCabinetRecordEnum;
import com.jeesite.modules.sd.common.constants.GlobalEnum;
import com.jeesite.modules.sd.common.constants.RecvConstant;
import com.jeesite.modules.sd.common.constants.RecvUppUnitEnum;
import com.jeesite.modules.sd.common.vo.DocRecvAnalse;
import com.jeesite.modules.sd.common.vo.DocReturnVo;
import com.jeesite.modules.sd.common.vo.DocUrge;
import com.jeesite.modules.sd.entity.*;
import com.jeesite.modules.sd.service.DocDeliverRecordService;
import com.jeesite.modules.sd.service.DocRecvService;
import com.jeesite.modules.sd.service.FileCabinetRecordService;
import com.jeesite.modules.sd.service.UppUnitService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.sys.utils.PwdUtils;
import com.jeesite.modules.sys.utils.RoleUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 文件复制Controller
 * 拟办领文列表
 *
 * @author ysj
 * @version 2020-07-01
 */
@Controller
@RequestMapping(value = "${adminPath}/sd/docDeliverRecord")
public class DocDeliverRecordController extends BaseController {

    @Autowired
    private DocDeliverRecordService recordService;
    @Autowired
    private DocRecvService docRecvService;
    @Autowired
    private OfficeService officeService;

    @Autowired
    private UserService userService;

    @Autowired
    private EmpUserService empUserService;

    @Autowired
    private FileCabinetRecordService fileCabinetRecordService;
    @Autowired
    private UppUnitService uppUnitService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public DocDeliverRecord get(String id, boolean isNewRecord) {
        return recordService.get(id, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("sd:docDeliverRecord:view")
    @RequestMapping(value = {"list", ""})
    public String list(DocDeliverRecord docDeliverRecord, Model model) {
        model.addAttribute("docDeliverRecord", docDeliverRecord);
        return "modules/sd/docDeliverRecordList";
    }

    /**
     * 检查机构类型 只能有一个拟办单位秘书处
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "checkUnitType")
    @ResponseBody
    public String checkUnitType(String id) {
        if (StringUtils.isBlank(id)) {
            return "true";
        }
        int type = Integer.parseInt(id);
        int unit = Integer.parseInt(GlobalEnum.OFFICE_TYPE_PROPOSED.getKey());
        int msc = Integer.parseInt(GlobalEnum.OFFICE_TYPE_SECRETARIAT.getKey());
        if (type != unit && type != msc) {
            return "true";
        } else {
            Office office = new Office();
            Extend extend = new Extend();
            extend.setExtendS1(id);
            office.setExtend(extend);
            Long i = officeService.findCount(office);
            if (i >= 1) {
                return "false";
            } else {
                return "true";
            }

        }


    }


    /**
     * 查询拟办文件首页
     *
     * @param docDeliverRecord
     * @param model
     * @return
     */
    @RequiresPermissions("sd:docDeliverRecord:view")
    @RequestMapping(value = {"index", ""})
    public String index(DocDeliverRecord docDeliverRecord, Model model) {
        model.addAttribute("docDeliverRecord", docDeliverRecord);
        return "modules/sd/docDeliverRecodeIndex";
    }


    /**
     * 查询拟办文件首页
     *
     * @param docDeliverRecord
     * @param model
     * @return
     */
    @RequiresPermissions("sd:docDeliverRecord:view")
    @RequestMapping(value = {"toDocReturn", ""})
    public String toDocReturn(DocDeliverRecord docDeliverRecord, Model model) {
        model.addAttribute("docDeliverRecord", docDeliverRecord);
        return "modules/sd/docReturn";
    }

    /**
     * 领取文件
     *
     * @param lingwen    1临时领文 0正常领文
     * @param extendS1   警号
     * @param officeCode 单位编码
     * @param userName   用户姓名
     * @param userCode   用户编码
     * @param userId     保密员密码
     * @return
     */
    @RequiresPermissions("sd:docDeliverRecord:edit")
    @RequestMapping(value = "takeFiles")
    @ResponseBody
    public String take(String userName, String facePath, String lingwen, String extendS1, String officeCode, String userCode, String userId) {
        int i = Integer.parseInt(lingwen);


        if (facePath == "") {
            return renderResult(Global.FALSE, text("请先拍照"));
        }
        if (i == 1) {
            String secretKey = Global.getConfig("shiro.loginSubmit.secretKey");
            String password = DesUtils.decode(userId, secretKey);
            String loginCode = UserUtils.getUser().getPassword();
            if (!PwdUtils.validatePassword(password, loginCode)) {
                return renderResult(Global.FALSE, text("保密员密码不对"));
            }
            try {
                String emailNumber = officeService.get(officeCode).getExtend().getExtendS4();
                if (emailNumber.equals("0")) {
                    throw new RuntimeException("此单位不是领文单位");
                }


                FileCabinetRecord fileCabinetRecord = new FileCabinetRecord();
                long l = System.currentTimeMillis();
                fileCabinetRecord.setProcessCode(String.valueOf(l));
                fileCabinetRecord.setUserName(UserUtils.getUser().getUserName());
                fileCabinetRecord.setUserFace(facePath);
                fileCabinetRecord.setCabinetno(emailNumber);
                fileCabinetRecord.setRecordDate(new Date());
                //fileCabinetRecordService.save(fileCabinetRecord);
                //向柜子发送开门命令
                boolean b = fileCabinetRecordService.sendCabinetCommand(fileCabinetRecord);
                if (!b) {
                    fileCabinetRecord.setResponseStatus(FileCabinetRecordEnum.STATUS_FAILURE.getValue());
                    fileCabinetRecord.setResponseType(FileCabinetRecordEnum.TYPE_CABINET_OPEN_RESULT.getValue());
                    fileCabinetRecordService.save(fileCabinetRecord);
                    throw new RuntimeException("开门失败");
                }

                fileCabinetRecord.setResponseStatus(FileCabinetRecordEnum.STATUS_SUCCESS.getValue());
                fileCabinetRecord.setResponseType(FileCabinetRecordEnum.TYPE_CABINET_OPEN_RESULT.getValue());
                fileCabinetRecordService.save(fileCabinetRecord);
                //领取文件
                recordService.takeDoc(officeCode, userName, extendS1, facePath, null);
            } catch (Exception e) {
                return renderResult(Global.FALSE, text(e.getMessage()));
            }

        } else if (i == 0) {
            try {
                EmpUser empUser = empUserService.get(userCode);
                String officeCode1 = empUser.getEmployee().getOffice().getOfficeCode();
                recordService.takeDoc(officeCode1, userCode);
            } catch (Exception e) {
                return renderResult(Global.FALSE, text(e.getMessage()));
            }

        }
        return renderResult(Global.TRUE, text("文件领取成功"));
    }


    /**
     * 查询左边的树形结构(分发列表)
     *
     * @return
     */
    @RequestMapping(value = "treeData")
    @ResponseBody
    public List<Map<String, Object>> treeData(String isShowCode) {
        List<Map<String, Object>> mapList = ListUtils.newArrayList();
        List<Office> list;

        list = officeService.findList(new Office());
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            Map<String, Object> map = MapUtils.newHashMap();
            map.put("id", e.getOfficeCode());
            map.put("pId", e.getParentCode());
            map.put("name", e.getOfficeName());
            map.put("title", e.getOfficeName());
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 查出的树形只有送文单位
     *
     * @param isShowCode
     * @return
     */
    @RequestMapping(value = "treeDataSend")
    @ResponseBody
    public List<Map<String, Object>> treeDataNb(String isShowCode) {
        List<Map<String, Object>> mapList = ListUtils.newArrayList();
        List<Office> list;
        Office office = new Office();
        Extend extend = new Extend();
        extend.setExtendS1(GlobalEnum.OFFICE_TYPE_SEND.getKey());
        office.setExtend(extend);
        list = officeService.findList(office);
        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            Map<String, Object> map = MapUtils.newHashMap();


            if (!"0".equals(e.getParentCode())) {
                map.put("id", e.getOfficeCode());
                map.put("pId", e.getParentCode());
                map.put("name", e.getOfficeName());
                map.put("title", e.getOfficeName());
                mapList.add(map);
            }

        }
        return mapList;
    }

    /**
     * 查询左边的树形结构(领文 带还文 已还文)
     *
     * @return
     */
    @RequestMapping(value = "treeDataPage")
    @ResponseBody
    public List<Map<String, Object>> treeDataPage(String isShowCode) {
        List<Map<String, Object>> mapList = ListUtils.newArrayList();
        List<Office> list;
        Office office = new Office();
        office.getSqlMap().getWhere().andBracket("extend_s1", QueryType.EQ, GlobalEnum.OFFICE_TYPE_GET.getKey(), 1).or("extend_s1", QueryType.EQ, GlobalEnum.OFFICE_TYPE_SEND.getKey(), 2).endBracket();
        list = officeService.findList(office);


        for (int i = 0; i < list.size(); i++) {
            Office e = list.get(i);
            Map<String, Object> map = MapUtils.newHashMap();
            map.put("id", e.getOfficeCode());
            map.put("pId", e.getParentCode());
            map.put("name", e.getOfficeName());
            map.put("title", e.getOfficeName());
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("sd:docDeliverRecord:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<DocDeliverRecord> listData(DocDeliverRecord docDeliverRecord, HttpServletRequest request, HttpServletResponse response) {
        docDeliverRecord.setPage(new Page<>(request, response));
        // String str=docDeliverRecord.getRecvUnitCode();

        docDeliverRecord.setDeliverType(GlobalEnum.RECORD_DELIVER_TYPE_PROPOSED.getKey());
        docDeliverRecord.getSqlMap().getWhere().and("take_date", QueryType.IS_NULL, null);
        Page<DocDeliverRecord> page = recordService.findPage(docDeliverRecord);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("sd:docDeliverRecord:view")
    @RequestMapping(value = "form")
    public String form(DocDeliverRecord docDeliverRecord, Model model, String id) {

        String str = docDeliverRecord.getDocRecv().getId();
        DocRecv docRecv = docRecvService.get(str);

        model.addAttribute("docRecv", docRecv);


        return "modules/sd/docDeliverHistoryShow";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("sd:docDeliverRecord:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated DocDeliverRecord docDeliverRecord) {
        recordService.save(docDeliverRecord);
        return renderResult(Global.TRUE, text("文件保存成功！"));

    }

    /**
     * 拟办领文
     *
     * @param docDeliverRecord
     * @param userCode         如果正常领文 就是用户id
     * @param doi
     * @param showUserId
     * @param policeCode
     * @return
     */
    @RequiresPermissions("sd:docDeliverRecord:edit")
    @PostMapping(value = "takeFile")
    @ResponseBody
    public String takeFile(DocDeliverRecord docDeliverRecord, String userCode, String doi, String showUserId, String policeCode, String face) {
        User user = userService.get(userCode);
        if (ObjectUtils.isNotEmpty(user)) {
            try {
                recordService.takeFile(docDeliverRecord.getId(), doi, user);
                return renderResult(Global.TRUE, text("领文成功"));
            } catch (Exception e) {
                return renderResult(Global.FALSE, text("文件领取失败"));
            }
        } else {

            try {
                recordService.temporaryTakeFile(doi, docDeliverRecord.getId(), showUserId, policeCode, face);
                return renderResult(Global.TRUE, text("领文成功"));
            } catch (Exception e) {
                return renderResult(Global.FALSE, text("文件领取失败"));
            }

        }

    }

    /**
     * 领文
     *
     * @param id
     * @return
     */
    @RequiresPermissions("sd:docDeliverRecord:edit")
    @GetMapping(value = "take")
    public String take(String id, Model model) {

        DocDeliverRecord docDeliverRecord = new DocDeliverRecord();
        docDeliverRecord.setId(id);
        DocDeliverRecord docDeliverRecord1 = recordService.get(docDeliverRecord);
        DocRecv docRecv = new DocRecv();
        docRecv.setId(docDeliverRecord1.getDocId());
        DocRecv docRecv1 = docRecvService.get(docRecv);

        //拟办人员
        Extend extend = new Extend();
        extend.setExtendS1(GlobalEnum.OFFICE_TYPE_PROPOSED.getKey());
        Office office = new Office();
        office.setExtend(extend);
        List<Office> list = officeService.findList(office);
        Office office2 = list.get(0);
        String officeCode = office2.getOfficeCode();


        List<Employee> empUsers = recordService.searchUserByOffice(officeCode);

        model.addAttribute("empList", empUsers);
        model.addAttribute("docRecv", docRecv1);
        model.addAttribute("doid", id);

        return "modules/sd/docDeliverSureTake";
    }

    /**
     * 拟办还文
     *
     * @param id
     * @param model
     * @return
     */
    @RequiresPermissions("sd:docDeliverRecord:edit")
    @GetMapping(value = "return")
    public String returnFile(String id, Model model) {
        DocDeliverRecord docDeliverRecord1 = new DocDeliverRecord();
        docDeliverRecord1.setId(id);
        DocDeliverRecord docDeliverRecord = recordService.get(docDeliverRecord1);
        DocRecv docRecv1 = new DocRecv();
        docRecv1.setId(docDeliverRecord.getDocId());
        DocRecv docRecv = docRecvService.get(docRecv1);
        Extend extend = new Extend();
        extend.setExtendS1(GlobalEnum.OFFICE_TYPE_PROPOSED.getKey());
        Office office = new Office();
        office.setExtend(extend);
        List<Office> list = officeService.findList(office);
        Office office2 = list.get(0);
        String officeCode = office2.getOfficeCode();
        List<Employee> empUsers = recordService.searchUserByOffice(officeCode);
        model.addAttribute("empList", empUsers);
        model.addAttribute("docRecv", docRecv);
        model.addAttribute("doid", id);
        return "modules/sd/docDeliverSureReturn";
    }


    /**
     * 校验机构邮箱是否存在
     *
     * @param email
     * @return
     */
    @GetMapping(value = "check")
    @ResponseBody
    public String check(String email) {


        if (!"0".equals(email)) {
            Office office = new Office();
            Extend extend = new Extend();
            extend.setExtendS4(email);
            office.setExtend(extend);
            long count = officeService.findCount(office);

            extend.setExtendS4(email);
            office.setExtend(extend);
            if (count >= 1) {
                return "false";
            } else {
                return "true";
            }
        } else {
            return "true";
        }
    }


    /**
     * 查询领文单位树形结构数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/takeOffice")
    public List<Map<String, Object>> treeData() {
        List<Map<String, Object>> mapList = ListUtils.newArrayList();
        Office where = new Office();
        Extend extend = new Extend();
        extend.setExtendS1(RecvConstant.IS_SEND_UNIT_FALSE);
        extend.setExtendS2("0");
        extend.setExtendS3("0");
        where.setStatus("0");
        where.setExtend(extend);
        List<Office> list = officeService.findList(where);
        for (int i = 0; i < list.size(); ++i) {
            Office e = list.get(i);
            if ("0".equals(e.getStatus())) {
                Map<String, Object> map = MapUtils.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentCode());
                //邮箱编号
                map.put("name", e.getExtend().getExtendS4());
                map.put("title", e.getFullName());
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 拟办文件批量领取
     *
     * @param userCodes
     * @param data
     * @return
     */
    @RequiresPermissions("sd:docDeliverRecord:edit")
    @RequestMapping(value = "batchFiles")
    @ResponseBody
    public String batchFiles(String[] data, String userName, String userPolice, String face, String userCodes) {
        if (data.length == 0) {
            return renderResult(Global.FALSE, text("领取失败"));
        }

        if (!"".equals(userCodes)) {
            User user = userService.get(userCodes);
            for (int i = 0; i < data.length; i++) {
                DocDeliverRecord doc = recordService.get(data[i]);
                String docId = doc.getDocId();
                recordService.takeFile(docId, data[i], user);
            }
            return renderResult(Global.TRUE, text("领取成功"));
        } else {

            for (int i = 0; i < data.length; i++) {
                DocDeliverRecord doc = recordService.get(data[i]);
                String docId = doc.getDocId();
                recordService.temporaryTakeFile(data[i], docId, userName, userPolice, face);
            }

            return renderResult(Global.TRUE, text("领取成功"));
        }
    }

    /**
     * 查询待还文件信息
     *
     * @param fileId
     * @return
     */
    @RequestMapping("getReturnDocInfo")
    @RequiresPermissions("sd:docDeliverRecord:edit")
    @ResponseBody
    public String getReturnDocInfo(String fileId) {
        DocCodeDTO code;
        try {

            String key = Global.getConfig("doc.code.aeskey");
            if (com.jeesite.common.lang.StringUtils.isEmpty(key)) {
                logger.error("解密二维码时查询到key为空");
                return renderResult(Global.FALSE, "此二维码异常!");
            }
            //解密
            String decodeStr = AesUtils.decode(fileId, key);
            code = JSON.parseObject(decodeStr, DocCodeDTO.class);
        } catch (Exception e) {
            return renderResult(Global.FALSE, "此二维码异常!");
        }

        if (Objects.isNull(code)) {
            return renderResult(Global.FALSE, "请先输入文件相关信息!");
        }

        if (StringUtils.isEmpty(code.getRecordId())) {
            return renderResult(Global.FALSE, "此二维码信息缺失!");
        }

        //获取文件信息
        DocDeliverRecord record = recordService.get(code.getRecordId());
        if (Objects.isNull(record)) {
            return renderResult(Global.FALSE, "没有此文件,尝试重新扫描!");
        }

        if (Objects.isNull(record.getTakeDate())) {
            return renderResult(Global.FALSE, "此文件尚未领取!");
        }
        if (Objects.nonNull(record.getReturnDate())) {
            return renderResult(Global.FALSE, "此文件已归还!");
        }
        //判断是否为领文或送文
        if (!(record.getDeliverType().equals(GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey())
                || record.getDeliverType().equals(GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey()))) {
            return renderResult(Global.FALSE, "文件信息有误!");
        }
        //获取单位用户信息
        EmpUser empUser = new EmpUser();
        empUser.getEmployee().getOffice().setIsQueryChildren(true);
        //判断是否为秘书处的人来还文 查询秘书处单位Code
        if (record.getOffice().getExtend().getExtendS1().equals(GlobalEnum.OFFICE_TYPE_SEND.getKey())) {
            String officeCode = recordService.getSecretariatOfficeCode(GlobalEnum.OFFICE_TYPE_SECRETARIAT.getKey());
            empUser.setCodes(new String[]{officeCode});
        } else {
            empUser.setCodes(new String[]{record.getRecvUnitCode()});
        }
        List<EmpUser> list = empUserService.findUserListByOfficeCodes(empUser);
        DocReturnDTO docReturnDTO = new DocReturnDTO();

        //设置用户信息
        if (CollectionUtils.isNotEmpty(list)) {
            EmpUser officeUser = list.get(0);
            docReturnDTO.setUserName(officeUser.getUserName())
                    .setUserCode(officeUser.getUserCode())
                    .setPoliceNo(userService.get(officeUser.getUserCode()).getExtend().getExtendS1());
        }

        docReturnDTO.setRecordId(record.getId())
                .setFileTitle(record.getDocRecv().getDocTitle())
                .setFileNo(record.getDocRecv().getDocFullNum())
                .setTakeUnitName(record.getOffice().getOfficeName());
        return renderResult(Global.TRUE, "查询成功!请对比归还文件信息", docReturnDTO);
    }

    /**
     * 还文
     *
     * @param docReturnVo
     * @return
     */
    @ResponseBody
    @RequestMapping("returnDoc")
    @RequiresPermissions("sd:docDeliverRecord:edit")
    public String returnDoc(DocReturnVo docReturnVo) {
        if (ArrayUtils.isEmpty(docReturnVo.getId())) {
            return renderResult(Global.FALSE, "归还文件数据不能为空!");
        }
        if (StringUtils.isEmpty(docReturnVo.getPassword())) {
            return renderResult(Global.FALSE, "操作员密码不能为空!");
        }

        //用户输入的密码和数据库中密码对比
        String password = docReturnVo.getPassword();
        String secretKey = Global.getConfig("shiro.loginSubmit.secretKey");
        password = DesUtils.decode(password, secretKey);
        User currUser = UserUtils.getUser();
        if (!PwdUtils.validatePassword(password, currUser.getPassword())) {
            return renderResult(Global.FALSE, "密码错误!");
        }

        User user = new User();
        //正常还文
        if (StringUtils.isNotEmpty(docReturnVo.getUserCode())) {
            user = userService.get(docReturnVo.getUserCode());
        } else {
            Extend extend = new Extend();
            user.setExtend(extend);
            user.setUserName(docReturnVo.getUserName());
            user.getExtend().setExtendS1(docReturnVo.getPoliceNo());
            user.getExtend().setExtendS3(docReturnVo.getPictureSrc());
        }
        try {
            recordService.batchReturnDoc(user, docReturnVo.getId());
            return renderResult(Global.TRUE, "文件归还成功!共计:" + docReturnVo.getId().length + "份文件;");
        } catch (Exception e) {
            logger.error("归还文件出错:",e);
            return renderResult(Global.FALSE, e.getMessage());
        }

    }

    /**
     * 查询不返回信息(用于还文页初始化表单暂时未找到替代方法)
     */
    @RequestMapping("/getNull")
    public void getNullReturn() {

    }

    /**
     * 获取用户信息
     *
     * @param userCode 用户id
     * @return 返回用户信息
     */
    @RequestMapping("/getUserInfoByCode")
    @ResponseBody
    @RequiresPermissions("sd:docDeliverRecord:edit")
    public User getUserInfoByCode(String userCode) {
        return userService.get(userCode);
    }

    /**
     *跳转到来文角度分析图
     * @return
     */
    @RequestMapping("/tz")
    public String tz()
    {
        return "modules/sd/recvAnalysisEchart";
    }

    /**
     * 来文角度 分析统计图
     * @return
     */
    @RequestMapping("/recvAnalysis")
    @ResponseBody
    public List<DocRecvAnalse> recvAnalysis(String begin,String end) {
        List<DocRecvAnalse> docRecvs =new ArrayList<>();
        docRecvs=docRecvService.recvAnalysis(begin,end);
        return docRecvs;
    }
    /**
     *跳转到分发角度分析图
     * @return
     */
    @RequestMapping("/toDistribute")
    public String tzSend() {
        return "modules/sd/distributeAnalysisEchart";

    }
    /**
     * 分发角度 分析统计图
     * @return
     */
    @RequestMapping("/sendAnalysis")
    @ResponseBody
    public List<DocRecvAnalse> sendAnalysis(String begin,String end) {
        List<DocRecvAnalse> docRecvs =new ArrayList<>();
        docRecvs=docRecvService.sendAnalysis(begin,end);
        return docRecvs;
    }

    /**
     * 验证保密员登录账号密码 secretMember 123456
     *
     * @param loginCode 登录账号
     * @param password  密码
     * @return 验证结果 true/false
     */
    @RequestMapping("/authSecretUser")
    @ResponseBody
    @RequiresPermissions("sd:docDeliverRecord:edit")
    public String authSecretUser(String loginCode, String password) {
        if (StringUtils.isEmpty(password)) {
            return renderResult(Global.FALSE, "无效密码!");
        }
        User user = new User();
        user.setLoginCode(loginCode);
        user = userService.getByLoginCode(user);
        if (ObjectUtils.isEmpty(user)) {
            return renderResult(Global.FALSE, "保密员账号输入有误!");
        }
        //验证用户是否为保密员
        if (!RoleUtils.hasUserRole(user.getUserCode(), RecvConstant.SECRET_MEMBER)) {
            return renderResult(Global.FALSE, "当前用户不是保密员!");
        }
        //解密用户输入的密码
        String secretKey = Global.getConfig("shiro.loginSubmit.secretKey");
        password = DesUtils.decode(password, secretKey);
        //用户输入的密码和数据库中密码对比
        if (PwdUtils.validatePassword(password, user.getPassword())) {
            return renderResult(Global.TRUE, "验证成功!");
        } else {
            return renderResult(Global.FALSE, "密码错误!");
        }

    }

    /**
     * 上级单位对树的封装
     * @param isShowCode
     * @param isTop
     * @return
     */
    @RequestMapping(value = "treeData1")
    @ResponseBody
    public List<Map<String, Object>> treeData(String isShowCode,@RequestParam(value = "isTop",defaultValue = "false") Boolean isTop) {
        List<Map<String, Object>> mapList = ListUtils.newArrayList();
        List<UppUnit> list;
        if (isTop) {
            list = new ArrayList<>();
        } else {
            list = uppUnitService.findList(new UppUnit());

        }
        for (UppUnit e : list) {
            Map<String, Object> map = MapUtils.newHashMap();
            map.put("id", e.getId());
            map.put("pId", e.getUnitType());
            map.put("name", com.jeesite.common.lang.StringUtils.getTreeNodeName(isShowCode, e.getId(), e.getUnitName()));
            map.put("title", e.getUnitName());
            mapList.add(map);
        }
        return mapList;
    }

    /**
     *跳转到统计页面
     * @return
     */
    @RequestMapping("/toStatistics")
    public String toStatistics() {

        return "modules/sd/statistics";

    }

    /**
     * 从来文角度进行统计
     * @return
     */
    @RequestMapping("/recvFind")
    @ResponseBody
    public int recvFind(String lwStart,String lwEnd,String[] testUserCode,String lwSecLvl,String lwEmergLvl) {
        System.out.printf("11");
        String lengthCode="";
        if(ArrayUtils.isNotEmpty(testUserCode)){
            lengthCode="1";
        }
        return  recordService.rescStatistics(lwStart, lwEnd, testUserCode, lwSecLvl, lwEmergLvl,lengthCode);

    }
    /**
     * 收文单位树
     * @return
     */
    @RequestMapping("/getFileUnitTree")
    @ResponseBody
    public List<Map<String, Object>> getFileUnitTree(String isShowCode,@RequestParam(value = "isTop",defaultValue = "false") Boolean isTop) {
        List<Map<String, Object>> mapList = ListUtils.newArrayList();
        List<Office> list;
        Office office=new Office();
        if (isTop) {
            list = new ArrayList<>();
        } else {
            office.getSqlMap().getWhere().andBracket("extend_s1",QueryType.EQ,GlobalEnum.OFFICE_TYPE_GET.getKey(),1).or("extend_s1",QueryType.EQ,GlobalEnum.OFFICE_TYPE_SEND.getKey(),2).endBracket();
            list = officeService.findList(office);

        }
        for (Office e : list) {
            Map<String, Object> map = MapUtils.newHashMap();
            map.put("id", e.getOfficeCode());
            map.put("pId", e.getParentCode());
            map.put("name", e.getOfficeName());
            map.put("title", e.getOfficeName());
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 文件分发统计
     * @param fenStart
     * @param fenEnd
     * @param testUserCode
     * @param takeUser
     * @param returnUser
     * @return
     */
    @RequestMapping("/recvSelect")
    @ResponseBody
    public int recvSelect(String fenStart,String fenEnd,String[] testUserCode,String takeUser,String returnUser) {

        String lengthCode="";
        if(ArrayUtils.isNotEmpty(testUserCode)){
            lengthCode="1";
        }
        return  recordService.distribStatistics(fenStart,fenEnd,testUserCode,takeUser,returnUser,lengthCode);

    }

    /**
     *催领催还
     * @param urgeStart
     * @param urgeEnd
     * @param recvCode
     * @return
     */
    @RequestMapping("/urgeSelect")
    @ResponseBody
    public DocUrge urgeSelect(String urgeStart,String urgeEnd,String recvCode) {
        System.out.printf("11");
        DocUrge docUrge = recordService.urgeTake(urgeStart, urgeEnd, recvCode);
        return  docUrge;
    }

    /**
     * 销毁情况统计
     * @param destroyStart
     * @param destroyEnd
     * @return
     */
    @RequestMapping("/destroySelect")
    @ResponseBody
    public int destroySelect(String destroyStart,String destroyEnd) {
        return  recordService.destoryStatistics( destroyStart, destroyEnd);
    }
}